package risk.client.logic;

import risk.client.Risk;

/**
 * @author: Johan
 */
public class Battle {
    private Army attacker;
    private Army defender;
    private Dice dice;
    private Risk risk;
    
    /**
     * Create a new Battle
     * 
     * @author: Johan
     * @param attacker
     * @param defender
     * @param risk
     */
    public Battle(Army attacker, Army defender, Risk risk) {
        this.attacker = attacker;
        this.defender = defender;
        this.dice = new Dice();
        this.risk = risk;
        
        // Start the battleloop if owners are not the same
        if(attacker.getOwner() != defender.getOwner()) {
            battleLoop();
        }
    }

    /**
     * The battle, handles the battle
     * 
     * @author: Johan
     */
    private void battleLoop() {
        risk.frame.labelStatus.setText("Status: Starting battleLoop");
        
        while(true) {
            
            // If attacker has less than 2 units, defender wins
            if(this.attacker.getUnits() < 2) {
                risk.frame.labelStatus.setText("Status: Defender Wins");
                break;
            } else if(this.defender.getUnits() < 1) { // If defender is out of units, attacker wins
                this.defender.setOwner(attacker.getOwner());
                this.attacker.moveArmy(this.defender, this.attacker.getUnits()-1);
                risk.frame.labelStatus.setText("Status: Attacker winns");
                risk.board.repaint();
                break;
            } else { // else, battle continues
                battleTurn();
            }
        }
    }

    /**
     * Do a turn by throwing one dice each, and the army with the highest number wins, if equal defender wins
     * 
     * @author: Johan
     */
    private void battleTurn() {
        if(dice.throwDice() > dice.throwDice()) { // attacker win
            defender.decreaseUnits(1);
        } else { // defender win
            attacker.decreaseUnits(1);
        }
    }
}
